<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <!-- <el-form-item label="风险单元id" prop="unitId">
          <el-input
            v-model="queryParams.unitId"
            placeholder="请输入风险单元id"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      <!-- <el-form-item label="危险有害元素" prop="hazardousElement">
          <el-input
            v-model="queryParams.hazardousElement"
            placeholder="请输入危险有害元素"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      <!-- <el-form-item label="事故原因" prop="accidentCause">
          <el-input
            v-model="queryParams.accidentCause"
            placeholder="请输入事故原因"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="造成后果" prop="consequence">
          <el-input
            v-model="queryParams.consequence"
            placeholder="请输入造成后果"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="影响范围" prop="impactScope">
          <el-input
            v-model="queryParams.impactScope"
            placeholder="请输入影响范围"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item> -->
      <!-- <el-form-item label="L值" prop="lValue">
        <el-input
          v-model="queryParams.lValue"
          placeholder="请输入L值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="E值" prop="eValue">
        <el-input
          v-model="queryParams.eValue"
          placeholder="请输入E值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="C值" prop="cValue">
        <el-input
          v-model="queryParams.cValue"
          placeholder="请输入C值"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item> -->
      <el-form-item label="风险等级" prop="riskLevel">
        <el-input
          v-model="queryParams.riskLevel"
          placeholder="请输入风险等级"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评估时间" prop="assessmentTime">
        <el-date-picker
          clearable
          v-model="queryParams.assessmentTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择评估时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="Export"
          >导出</el-button
        >
      </el-form-item>
    </el-form>

    <el-table
      v-loading="loading"
      :data="identificationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="风险辨识id" align="center" prop="identificationId" /> -->
      <el-table-column label="事故类型" align="center">
        <template slot-scope="scope">
          <template v-if="typeof scope.row.accidentType == 'string'">
            {{ scope.row.accidentType }}
          </template>

          <template v-else>
            <span
              v-for="(item, index) in scope.row.accidentType"
              :key="index"
              >{{ item + "、" }}</span
            >
          </template>
        </template>
      </el-table-column>

      <el-table-column
        label="辨识类型"
        align="center"
        prop="identificationType"
      >
        <template slot-scope="scope">
          <span>{{
            scope.identificationType == 1 ? "企业辨识" : "专业机构辨识"
          }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="风险单元id" align="center" prop="unitId" /> -->
      <el-table-column
        label="危险有害元素"
        align="center"
        prop="hazardousElement"
      />
      <el-table-column label="事故原因" align="center" prop="accidentCause" />
      <el-table-column label="造成后果" align="center" prop="consequence" />
      <el-table-column label="影响范围" align="center" prop="impactScope" />
      <el-table-column label="L值" align="center" prop="lValue" />
      <el-table-column label="E值" align="center" prop="eValue" />
      <el-table-column label="C值" align="center" prop="cValue" />
      <el-table-column label="风险等级" align="center" prop="riskLevel">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.riskLevel == '极度危险'" type="danger" effect="dark">{{ scope.row.riskLevel }}</el-tag>
          <el-tag v-if="scope.row.riskLevel == '高度危险'" type="danger" effect="dark">{{ scope.row.riskLevel }}</el-tag>
          <el-tag v-if="scope.row.riskLevel == '显著危险'" type="warning" effect="dark">{{ scope.row.riskLevel }}</el-tag>
          <el-tag v-if="scope.row.riskLevel == '一般危险'" type="" effect="dark">{{ scope.row.riskLevel }}</el-tag>
          <el-tag v-if="scope.row.riskLevel == '稍有危险'" type="">{{ scope.row.riskLevel }}</el-tag>
        </template>

      </el-table-column>
      <el-table-column
        label="评估时间"
        align="center"
        prop="assessmentTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.assessmentTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="管控状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.status == '1'" type="">已管控</el-tag>
          <el-tag v-if="scope.row.status == '0'" type="warning">未管控</el-tag>
        </template>

      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
      >
        <template slot-scope="scope">
          <!-- <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:identification:edit']"
            >修改</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="manage(scope.row)"
            v-hasPermi="['system:identification:edit']"
            >管控措施</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:identification:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改危险辨识对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="风险单元id" prop="unitId">
          <el-input v-model="form.unitId" placeholder="请输入风险单元id" />
        </el-form-item>
        <el-form-item label="辨识类型" prop="identificationType">
          <el-input v-model="form.unitId" placeholder="请输入风险辨识类型" />
        </el-form-item>
        <el-form-item label="危险有害元素" prop="hazardousElement">
          <el-input
            v-model="form.hazardousElement"
            placeholder="请输入危险有害元素"
          />
        </el-form-item>
        <el-form-item label="事故类型" prop="accidentType">
          <el-input v-model="form.accidentCause" placeholder="请输入事故类型" />
        </el-form-item>
        <el-form-item label="事故原因" prop="accidentCause">
          <el-input v-model="form.accidentCause" placeholder="请输入事故原因" />
        </el-form-item>
        <el-form-item label="造成后果" prop="consequence">
          <el-input v-model="form.consequence" placeholder="请输入造成后果" />
        </el-form-item>
        <el-form-item label="影响范围" prop="impactScope">
          <el-input v-model="form.impactScope" placeholder="请输入影响范围" />
        </el-form-item>
        <!-- <el-form-item label="L值" prop="lValue">
            <el-input v-model="form.lValue" placeholder="请输入L值" />
          </el-form-item>
          <el-form-item label="E值" prop="eValue">
            <el-input v-model="form.eValue" placeholder="请输入E值" />
          </el-form-item>
          <el-form-item label="C值" prop="cValue">
            <el-input v-model="form.cValue" placeholder="请输入C值" />
          </el-form-item> -->
        <!-- <el-form-item label="风险等级" prop="riskLevel">
            <el-input v-model="form.riskLevel" placeholder="请输入风险等级" />
          </el-form-item> -->
        <!-- <el-form-item label="评估时间" prop="assessmentTime">
            <el-date-picker clearable
              v-model="form.assessmentTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择评估时间">
            </el-date-picker>
          </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="title"
      :visible.sync="manageList"
      width="500px"
      append-to-body
    >
      <el-form
        :model="manageForm"
        label-width="80px"
        ref="userForm"
        :rules="userRules"
      >
        <el-divider>责任人</el-divider>

        <el-form-item label="责任部门">
          <!-- <el-input v-model="form.unitId" placeholder="请输入风险单元id" /> -->
          <el-cascader
            placeholder="试试搜索"
            :options="deptOptions"
            :props="{ value: 'id' }"
            @change="cascaderChange"
            filterable
          ></el-cascader>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="责任人" prop="uid">
              <el-select
                v-model="manageForm.uid"
                placeholder="请选择责任人"
                filterable
              >
                <el-option
                  v-for="item in userSelectList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <span style="color:#F56C6C">*请先选择部门后选择对应责任人(支持搜索)</span>
          </el-col>
          <el-col :span="4" :offset="0">
            <el-button type="primary" @click="manageSub">新增</el-button>
          </el-col>
        </el-row>

        <el-table :data="manageTable">
          <el-table-column label="序号" type="index" />
          <el-table-column label="责任人" align="center" prop="userName" />
          <el-table-column label="部门" align="center" prop="deptName" />
          <!-- <el-table-column label="管控措施" align="center" prop="remake" /> -->
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="180"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="deleteMangeUser(scope.row)"
                v-hasPermi="['system:level:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <el-divider>管控措施</el-divider>
      <el-form
        :model="manageContentForm"
        label-width="80px"
        ref="contentForm"
        :rules="contentRules"
      >
        <el-form-item label="管控类型" prop="controlType">
          <el-select
            v-model="manageContentForm.controlType"
            placeholder="请选择管控类型"
            filterable
          >
            <el-option label="管理措施" value="管理措施"></el-option>
            <el-option label="个体防护" value="个体防护"></el-option>
            <el-option label="应急处置" value="应急处置"></el-option>
            <el-option label="工程技术" value="工程技术"></el-option>
            <el-option label="培训教育" value="培训教育"></el-option>
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="16">
            <el-form-item label="管控内容" prop="controlContent">
              <el-input
                type="textarea"
                v-model="manageContentForm.controlContent"
                placeholder="请输入管控内容"
              />
            </el-form-item>
          </el-col>
          <el-col :span="4" :offset="4">
            <el-button type="primary" @click="manageContentSub">新增</el-button>
          </el-col>
        </el-row>

        <el-table :data="manageContentTable">
          <el-table-column label="序号" type="index" />
          <el-table-column label="管控类型" align="center" prop="controlType" />
          <el-table-column
            label="管控措施"
            align="center"
            prop="controlContent"
          />
          <el-table-column
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="180"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="deleteMangeContent(scope.row)"
                v-hasPermi="['system:level:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </el-dialog>
  </div>
</template>
  
  <script>
import {
  listIdentification,
  getIdentification,
  delIdentification,
  addIdentification,
  updateIdentification,
  triUser,
  triControl,
  managerList,
  delTriUser,
  delTriContent,
  delTriContentExport
} from "@/api/system/identification";
import { listUser, deptTreeSelect } from "@/api/system/user";
export default {
  name: "Identification",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //管控
      manageList: false,
      deptOptions: [],
      userSelectList: [],
      manageForm: {
        rid: null,
        uid: null,
        // controlType: null,
        // controlContent: null,
      },
      manageContentForm: {
        rid: null,
        // uid: null,
        controlType: null,
        controlContent: null,
      },
      manageTable: [],
      manageContentTable: [],
      userRules: {
        uid: [{ required: true, message: "请选择部门后确定责任人", trigger: "blur" }],
      },
      contentRules: {
        controlType: [{ required: true, message: "请选择管控类型", trigger: "blur" }],
        controlContent: [{ required: true, message: "请选择管控内容", trigger: "blur" }],
      },
      manageListID: null,
      // 危险辨识表格数据
      identificationList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        identificationType: null,
        unitId: null,
        hazardousElement: null,
        accidentType: null,
        accidentCause: null,
        consequence: null,
        impactScope: null,
        lValue: null,
        eValue: null,
        cValue: null,
        riskLevel: null,
        assessmentTime: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询危险辨识列表 */
    getList() {
      this.loading = true;
      listIdentification(this.queryParams).then((response) => {
        this.identificationList = response.rows;
        this.identificationList.forEach((item) => {
          // console.log(
          //   item.accidentType,
          //   typeof item.accidentType,
          //   item.accidentType.charAt(0)
          // );
          if (item.accidentType.charAt(0) == "[") {
            item.accidentType = JSON.parse(item.accidentType);
          }
        });
        //   this.identificationList.accidentType = JSON.parse(response.rows.accidentType)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        identificationId: null,
        identificationType: null,
        unitId: null,
        hazardousElement: null,
        accidentType: null,
        accidentCause: null,
        consequence: null,
        impactScope: null,
        lValue: null,
        eValue: null,
        cValue: null,
        riskLevel: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        assessmentTime: null,
        status: null,
      };
      this.resetForm("form");
    },
    Export(){
      delTriContentExport().then(res=>{
        console.log(res);
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.identificationId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加危险辨识";
    },
    //   管控
    manage(row) {
      this.manageForm.rid = row.identificationId;
      this.manageContentForm.rid = row.identificationId;
      this.manageListID = row.identificationId;
      this.manageList = true;
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
      this.getTableList(row.identificationId);
    },
    async getTableList(id) {
      await managerList(id).then((res) => {
        this.manageTable = res.data.riskIdentificationUsers;
        this.manageContentTable = res.data.riskIdentificationControls;
        this.manageTable.forEach((item, index) => {
          item.remake =
            res.data.riskIdentificationControls[index].controlContent;
        });
      });

      console.log(this.manageTable);
    },
    cascaderChange(data) {
      console.log(data);
      // pageNum=1&pageSize=6&peopleType=1&deptId=105
      listUser({
        deptId: data[data.length - 1],
        // pageNum: 1,
        // pageSize: 1,
        peopleType: 1,
      }).then((res) => {
        this.userSelectList = res.rows;
      });
    },
    manageSub() {
      this.$refs["userForm"].validate(async (valid) => {
        if (valid) {
          await triUser(this.manageForm).then((res) => {
            console.log(res, "userrrrrrrrrrrrrrrrrrr");
            if (res.code == 200) {
              // this.manageList = false;
              this.manageForm = {
                rid: this.manageForm.rid,
                uid: null,
              };
            }
          });
          await this.getTableList(this.manageForm.rid)
          this.$refs["userForm"].resetFields()
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    manageContentSub() {
      this.$refs["contentForm"].validate(async (valid) => {
        if (valid) {
          await triControl(this.manageContentForm).then(res => {
            console.log(res, "conterrrrrrrrrrrrrrrrrrrr");
            if (res.code == 200) {
              // this.manageList = false;
              this.manageContentForm = {
                rid: this.manageContentForm.rid,
                // uid: null,
                controlType: null,
                controlContent: null,
              };
            }
          });
          await this.getTableList(this.manageContentForm.rid)
          this.$refs["contentForm"].resetFields()

        }else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    deleteMangeUser(row) {
      console.log(row);
      delTriUser(row.id).then((res) => {
        if (res.code == 200) {
          this.getTableList(this.manageListID);
        }
      });
    },
    deleteMangeContent(row) {
      console.log(row);
      delTriContent(row.id).then((res) => {
        if (res.code == 200) {
          this.getTableList(this.manageListID);
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const identificationId = row.identificationId || this.ids;
      getIdentification(identificationId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改危险辨识";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.identificationId != null) {
            updateIdentification(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addIdentification(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const identificationIds = row.identificationId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除危险辨识编号为"' + identificationIds + '"的数据项？'
        )
        .then(function () {
          return delIdentification(identificationIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/identification/export",
        {
          ...this.queryParams,
        },
        `identification_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style scoped>
::v-deep(.el-dialog__body) {
  padding: 7px 20px !important;
}
</style>  